/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.mail.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.mail.entity.Mail;
import org.springblade.modules.mail.mapper.MailMapper;
import org.springblade.modules.mail.service.IMailService;
import org.springblade.modules.mail.vo.MailVO;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * 邮箱配置表 服务实现类
 *
 * @author Blade
 * @since 2020-12-18
 */
@Service
@AllArgsConstructor
public class MailServiceImpl extends BaseServiceImpl<MailMapper, Mail> implements IMailService {

	private final RedisUtil redisUtil;

    @Override
    public IPage<MailVO> selectMailPage(IPage<MailVO> page, Mail mail) {
        List<MailVO> mailS = baseMapper.selectMailPage(page, mail);
        List<MailVO> mailVOList = new ArrayList<>();
        for (MailVO mailVO : mailS) {
            mailVO.setIsUse(mailVO.getStatus()==0?"启用":"停用");
            mailVOList.add(mailVO);
        }
        return page.setRecords(mailVOList);
    }

    /**
     * 发送邮件
     *
     * @param mail
     * @return
     */
    @Override
    public boolean mailGo(String mail) throws UnsupportedEncodingException, GeneralSecurityException, MessagingException {
        String code = StringUtil.random(6, RandomType.INT);
        email(code, mail);
        redisUtil.set("mail:" + mail, code, 5, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public boolean mailMessage(String mail, int mailCode) {
        Object o = redisUtil.get("mail:" + mail);
        boolean equals = Func.toStr(o).equals(Func.toStr(mailCode));
        if (equals) {
            redisUtil.del("mail:" + mail);
        }
        return equals;
    }

    @Override
    public boolean mailStart(Long id) {
        List<Mail> list = list(Wrappers.<Mail>query().lambda().ne(Mail::getId, id));
        for (Mail mail : list) {
            mail.setStatus(1);
            updateById(mail);
        }
        Mail mail = getById(id);
        mail.setStatus(0);
        return updateById(mail);
    }


    public void email(String code, String mail) throws GeneralSecurityException, MessagingException, UnsupportedEncodingException {
        Properties prop = new Properties();
        //设置QQ邮件服务器
        prop.setProperty("mail.host", "smtp.qq.com");
        // 邮件发送协议
        prop.setProperty("mail.transport.protocol", "smtp");
        // 需要验证用户名密码
        prop.setProperty("mail.smtp.auth", "true");
        // 关于QQ邮箱，还要设置SSL加密，加上以下代码即可
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        //使用JavaMail发送邮件的5个步骤
        //创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("发件人邮件用户名", "授权码");
            }
        });
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com", "邮箱的用户名", "授权码");
        //4、创建邮件
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress("发件人", "发件人名称", "UTF-8"));
        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail));
        //邮件的标题
        message.setSubject("邮箱验证码");
        //邮件的文本内容
        message.setContent("您的邮箱验证码为：【" + code + "】,5分钟会失效哦，打死不告诉别人！", "text/html;charset=UTF-8");
        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }
}
